/**
 *
 * Created at 20160309 by Lien Z
 *
 */

(function ($) {


    $(function (win) {
        'use strict';

        var AJAX_CAR_URL = system.api_domain + "/get_option?category=carmodel";
        var AJAX_REGION_URL = system.api_domain +  "/get_option?category=region";

        var regionPicker = {
            pickerCollection: [],

            init: function () {

                if (this.__checkPickerExist()) {
                    this
                        .makePickerCollection()
                        .getInitialRegion()
                        .__bindEvent()
                        .__checkIfDefaultProvince();
                } else {
                    return
                }
            },

            __checkIfDefaultProvince: function () {
                this.pickerCollection.forEach(function (picker) {
                    if (picker.province && picker.province.data('defaults')) {
                        $(picker.province).trigger('change', [picker.province.data('defaults')]);
                    }
                });

                return this;
            },

            getInitialRegion: function () {
                this.__getRegion().province();
                return this;
            },

            __makeOptions: function (optionsData, defaultValue) {
                var options = '';

                var makeNormalOption = function (optionData) {
                    var option = [
                        "<option value='" + optionData.id + "'>", optionData.name, "</option>"
                    ].join('');

                    return option;
                };

                var makeSelectedOption = function (optionData) {
                    var option = [
                        "<option value='" + optionData.id + "' selected>", optionData.name, "</option>"
                    ].join('');

                    return option;
                };

                $.each(optionsData, function (idx, optionData) {
                    if (defaultValue && (defaultValue === Number(optionData.id))) {
                        options += makeSelectedOption(optionData);
                    } else {
                        options += makeNormalOption(optionData);
                    }
                });

                return options;
            },

            __getRegion: function () {
                var _this = this;

                var coreAjax = function (param, successCB) {
                    $.ajax({
                        url: AJAX_REGION_URL,
                        data: {pid: param},
                        dataType: 'jsonp',
                        type: 'GET',
                        success: function (dataset) {
                            if (dataset.status == 'success') successCB(dataset.data);
                        }
                    });
                };

                var coreProcess = function (dataset, regionName) {
                    _this.pickerCollection.forEach(function (picker) {
                        var options = '<option value="" selected>请选择</option>';
                        if (picker[regionName] && picker[regionName].data('defaults')) {
                            options += _this.__makeOptions(dataset, picker[regionName].data('defaults'))
                        } else {
                            options += _this.__makeOptions(dataset);
                        }
                        $(picker[regionName]).html(options);
                    });
                };

                return {
                    'province': function (successCB) {
                        return coreAjax(0, function (dataset) {
                            coreProcess(dataset, 'province');
                        });
                    },
                    'city': function (brandId, successCB) {
                        return coreAjax(brandId, function (dataset) {
                            coreProcess(dataset, 'city');
                        });
                    }
                };
            },

            __bindEvent: function () {
                this.__bindProvinceEvent();
                return this;
            },

            __bindProvinceEvent: function () {

                /**
                 *
                 * 为所有第一次省级下拉绑定 change 事件。
                 * 传入父级 blcok 作为 ref，for late use。
                 *
                 */
                this.pickerCollection.forEach(
                    function (picker) {
                        $(picker.block).on('change', '[name="province_id"]', {'picker': picker}, this.provinceDidChange.bind(this));
                    }.bind(this)
                );
            },

            provinceDidChange: function (e, defaultValue) {
                e.preventDefault();
                e.stopPropagation();

                var picker = e.data.picker;
                var $target = $(e.currentTarget);
                var $value = defaultValue || $target.val();

                this.__getRegion().city($value);
            },

            __checkPickerExist: function () {
                return $('select[name="province_id"]').length > 0;
            },

            makePickerCollection: function () {
                $('select[name="province_id"]').each(function (_, province) {
                    var pair = {
                        province: $(province),
                        block: $(province).parents('.form-picker'),
                        city: $(province).parents('.form-picker').find('select[name="city_id"]')
                    };
                    this.pickerCollection.push(pair);
                }.bind(this));

                return this;
            }
        };

        /**
         * CarPicker Class
         * @pickerBlock class 为 form-picker 的容器
         *
         */

        function CarPicker(pickerBlock) {
            this.block = pickerBlock;
            this.brand = $(this.block).find('select[name^="car_brand_id"]');
            this.series = $(this.block).find('select[name^="car_series_id"]');
            this.model = $(this.block).find('select[name^="car_model_id"]');
            this.init();
        }

        CarPicker.prototype = {
            init: function () {
                this.__bindEvent();
                this.getInitialBrands();
            },

            /* 获取车辆车型起始数据，所有品牌。 */
            getInitialBrands: function () {

                this.getOptions().brands(function (dataset) {
                    var flag = '<option value="" selected>请选择</option>';
                    var options;

                    if (this.brand && this.brand.data('defaults')) {
                        options = this.__makeOptions(dataset, this.brand.data('defaults'));
                    } else {
                        options = this.__makeOptions(dataset);
                    }

                    flag += options;
                    this.__fill().brand(flag);

                    this.__checkIfDefaultBrnad();
                    this.__checkIfDefaultSeries();
                }.bind(this));

            },

            __checkIfDefaultBrnad: function () {
                if (this.brand && this.brand.data('defaults'))
                    $(this.brand).trigger('change', [this.brand.data('defaults')]);
            },

            __checkIfDefaultSeries: function () {
                if (this.series && this.series.data('defaults'))
                    $(this.series).trigger('change', [this.series.data('defaults')]);
            },

            getOptions: function () {
                var core = function (param, successCB) {
                    $.ajax({
                        url: AJAX_CAR_URL,
                        data: {pid: param},
                        dataType: 'jsonp',
                        type: 'GET',
                        cache: false,
                        success: function (dataset) {
                            if (dataset.status == 'success') successCB(dataset.data);
                        }
                    });
                };

                return {
                    'brands': function (successCB) {
                        return core(0, successCB);
                    },
                    'series': function (brandId, successCB) {
                        return core(brandId, successCB);
                    },
                    'models': function (seriesId, successCB) {
                        return core(seriesId, successCB);
                    }
                }
            },

            __makeOptions: function (optionsData, defaultValue) {

                var options = '';

                var makeNormalOption = function (optionData) {
                    var option = [
                        "<option value='" + optionData.id + "'>", optionData.name, "</option>"
                    ].join('');

                    return option;
                };

                var makeSelectedOption = function (optionData) {
                    var option = [
                        "<option value='" + optionData.id + "' selected>", optionData.name, "</option>"
                    ].join('');

                    return option;
                };

                $.each(optionsData, function (idx, optionData) {
                    if (Number(optionData.id) === defaultValue) options += makeSelectedOption(optionData);
                    else options += makeNormalOption(optionData);
                });

                return options;
            },

            __fill: function () {
                var _this = this;

                var core = function (DOM, option) {
                    $(DOM).html(option);
                };

                return {
                    'brand': function (options) {
                        return core(_this.brand, options);
                    },
                    'series': function (options) {
                        return core(_this.series, options);
                    },
                    'model': function (options) {
                        return core(_this.model, options);
                    }
                }
            },

            __bindEvent: function () {
                // bind brand selector change
                $(this.block).on('change', 'select[name^="car_brand_id"]', this.brandDidChange.bind(this));

                // bind series selector change
                $(this.block).on('change', 'select[name^="car_series_id"]', this.seriesDidChange.bind(this));
            },

            brandDidChange: function (e, defaultValue) {
                e.preventDefault();
                e.stopPropagation();

                var $target = $(e.currentTarget);
                var param = defaultValue || $target.val();

                this.getOptions().series(param, function (dataset) {
                    var flag = '<option value="" selected>请选择</option>';
                    var options;

                    if (this.series.data('defaults')) options = this.__makeOptions(dataset, this.series.data('defaults'));
                    else options = this.__makeOptions(dataset);


                    flag += options;
                    this.__fill().series(flag);
                }.bind(this));
            },

            seriesDidChange: function (e, defaultValue) {
                e.preventDefault();
                e.stopPropagation();

                var $target = $(e.currentTarget);
                var param = defaultValue || $target.val();

                this.getOptions().models(param, function (dataset) {
                    var flag = '<option value="" selected>请选择</option>';
                    var options;

                    if (this.model && this.model.data('defaults'))
                        options = this.__makeOptions(dataset, this.model.data('defaults'));
                    else
                        options = this.__makeOptions(dataset);

                    flag += options;
                    this.__fill().model(flag);
                }.bind(this));
            }
        }

        var carPickerInitializer = function () {

            /* 产讯当前页面是否存在车辆选择联动 */
            var __checkPickerExist = function () {
                if ($('select[name^="car_brand_id"]').length > 0) return true;
                else return false;
            };

            /* 实例化*单个*车辆品牌对象 */
            var initializePicker = function (block) {
                var cp = new CarPicker(block);
            };

            /* 实例化*所有*车辆品牌对象 */
            var initialAllPicker = function () {
                $('select[name^="car_brand_id"]').each(function (idx, brandSelect) {
                    var block = $(brandSelect).parents('.form-picker')[0];
                    initializePicker(block);
                });
            };

            /* 调用 */
            if (__checkPickerExist()) initialAllPicker();
            else return;
        };


        /**
         *
         * 初始项目
         *
         */
        $(document).ready(function () {

            /* 初始化二级、三级地区选择联动*/
            regionPicker.init();

            /* 初始化二级、三级车型选择联动 */
            carPickerInitializer();

        });
    }(window));

}(jQuery));

(function ($) {
    $.getScript = function (src, func) {
        var script = document.createElement('script');
        script.async = "async";
        script.src = src;
        if (func) {
            script.onload = func;
        }
        document.getElementsByTagName("head")[0].appendChild(script);
    }
})(jQuery)






















